package uk.org.brindy.twitterwave;

import java.util.Arrays;
import java.util.logging.Logger;
import java.util.regex.Matcher;

import com.google.wave.api.AbstractRobotServlet;
import com.google.wave.api.Blip;
import com.google.wave.api.Range;
import com.google.wave.api.RobotMessageBundle;
import com.google.wave.api.TextView;
import com.google.wave.api.Wavelet;

@SuppressWarnings("serial")
public class TwitterWaveServlet extends AbstractRobotServlet {

	public static final Logger log = Logger.getLogger(TwitterWaveServlet.class
			.getName());

	private BlipProcessor hashtagProcessor = new BlipProcessor() {

		@Override
		protected void processMatch(TextView doc, Range range, Matcher match) {
			annotate(doc, range, "link/manual", TwitterUtil.HASHTAG_REPLACEMENT
					.concat(match.group(2)));
		}

		@Override
		protected String getPattern() {
			return TwitterUtil.HASHTAG_REGEX;
		}

	};

	private BlipProcessor usernameProcessor = new BlipProcessor() {

		@Override
		protected void processMatch(TextView doc, Range range, Matcher match) {
			annotate(doc, range, "link/manual",
					TwitterUtil.USERNAME_REPLACEMENT.concat(match.group(2)));
		}

		@Override
		protected String getPattern() {
			return TwitterUtil.USERNAME_REGEX;
		}

	};

	@Override
	public void processEvents(RobotMessageBundle bundle) {
		log.fine("processEvents IN");

		Wavelet wavelet = bundle.getWavelet();

		if (bundle.wasSelfAdded()) {
			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView
					.append("TwitterWaveBot v7 by brindy ( http://www.brindy.org.uk/ ) ready "
							+ "to link up #hashtags and @usernames.");
		}

		BlipProcessor.applyProcessorsToChangedBlips(Arrays.asList(
				hashtagProcessor, usernameProcessor), bundle,
				"twitterwavebot@appspot.com");

		log.fine("processEvents OUT");
	}
}
